import React, { useEffect } from 'react'
import { useImmer } from 'use-immer'
import Taro, { getCurrentInstance, useShareAppMessage, useShareTimeline } from '@tarojs/taro'
import qs from 'qs'
import { SpPage, SpSearch, SpTabbar } from '@/components'
import { getDistributorId } from '@/utils'
import { platformTemplateName } from '@/utils/platform'
import req from '@/api/req'
import HomeWgts from '@/pages/home/comps/home-wgts'
import './index.scss'

const initialState = {
  wgts: [],
  loading: true,
  shareInfo: null
}
function CustomPage() {
  const $instance = getCurrentInstance()
  const [state, setState] = useImmer(initialState)
  const { wgts, loading, shareInfo } = state
  useEffect(() => {
    fetch()
  }, [])

  const fetch = async () => {
    const pathparams = qs.stringify({
      template_name: platformTemplateName,
      version: 'v1.0.1',
      page_name: `custom_1`,
      distributor_id: getDistributorId()
    })
    const url = `/pageparams/setting?${pathparams}`
    const { config, share } = await req.get(url)
    setState((draft) => {
      draft.wgts = config
      draft.loading = false
      draft.shareInfo = share
    })
    // setNavigationBarTitle(share?.page_name)
    // Taro.setNavigationBarTitle({
    //   title: share?.page_name
    // })
    // this.setState(
    //   {
    //     positionStatus: (fixSetting.length && fixSetting[0].params.config.fixTop) || false
    //   },
    //   () => {
    //     this.fetchInfo()
    //   }
    // )
  }

  useShareAppMessage(async () => {
    return getAppShareInfo()
  })

  useShareTimeline(() => {
    return getAppShareInfo()
  })

  const getAppShareInfo = () => {
    const { id } = $instance.router.params
    const { userId } = Taro.getStorageSync('userinfo')
    const query = {
      shareUserId: userId,
      company_id: process.env.APP_COMPANY_ID,
      id: id
    }
    if (userId) query.uid = userId

    return {
      title: shareInfo.page_share_title,
      imageUrl: shareInfo.page_share_imageUrl,
      path:`/pages/custom/custom-page?${qs.stringify(query)}`,
      query: qs.stringify(query)
    }
  }
  const searchComp = wgts.find((wgt) => wgt.name == 'search')
  let filterWgts = []
  if (searchComp && searchComp.config.fixTop) {
    filterWgts = wgts.filter((wgt) => wgt.name !== 'search')
  } else {
    filterWgts = wgts
  }
  const fixedTop = searchComp && searchComp.config.fixTop
  const pageData = wgts.find((wgt) => wgt.name == 'page')
  return (
    <SpPage
      renderFooter={<SpTabbar />}
      scrollToTopBtn
      className='page-custom-page'
      loading={loading}
    >
      <HomeWgts wgts={filterWgts} pageName='custom_1' />
    </SpPage>
  )
}

CustomPage.options = {
  addGlobalClass: true
}

export default CustomPage
